using UnityEngine;
using QFramework;

namespace QFramework.Monk
{
	public enum MiniBossState
	{
		FollowPlayer,
		Idle,
		Wait,
		Dash,
	}
	public partial class MiniBoss : EnemyBase
	{
		private FSM<MiniBossState> fsm = new FSM<MiniBossState>();
		public float dashSpeed = 10f;
		
		protected override void Awake()
		{
			base.Awake();
			SetFsmState();
		}

		private void SetFsmState()
		{
			//加入状态机
			fsm.State(MiniBossState.FollowPlayer).OnFixedUpdate(() =>
			{
				if (!AppStart.CheckGameState(GameState.GamePlaying))
				{
					return;
				}
				// 空指针检查
				if (Player.Default != null)
				{
					// 计算位置差
					var distance = Vector3.Distance(Player.Default.transform.position, this.transform.position);
					if (distance<4f)
					{
						//进入下个状态
						fsm.ChangeState(MiniBossState.Idle);
					}
					else
					{
						
						Vector3 dir = (Player.Default.transform.position - this.transform.position).normalized;

						// 移动物体
						selfRigidbody2D.velocity = dir * mSpeed;
					}
				}
				else
				{
					selfRigidbody2D.velocity = Vector2.zero;
				}
			});
			fsm.State(MiniBossState.Idle).OnEnter(() =>
			{
				selfRigidbody2D.velocity = Vector2.zero;
			}).OnUpdate(()=>
			{
				//15-3 闪动颜色
				var frame = 3 + (60 * 2 - fsm.FrameCountOfCurrentState) / 10;
				if ((fsm.FrameCountOfCurrentState/frame)%2==0)
				{
					mSprite.color = Color.green;
				}
				else
				{
					mSprite.color = Color.white;
				}
				if (fsm.FrameCountOfCurrentState>=60*2)//发呆2秒
				{
					//进入下个状态
					fsm.ChangeState(MiniBossState.Dash);
				}
			}).OnExit(() =>
			{
				mSprite.color = Color.white;
			});

			fsm.State(MiniBossState.Wait).OnEnter(() =>
			{
				selfRigidbody2D.velocity = Vector2.zero;
			}).OnUpdate(()=>
			{
				if (fsm.FrameCountOfCurrentState>=60)//等待1秒
				{
					//进入下个状态
					fsm.ChangeState(MiniBossState.FollowPlayer);
				}
			});
			
			var dashDir = Vector3.zero;
			fsm.State(MiniBossState.Dash).OnEnter(() =>
			{
				if (Player.Default != null)
				{
					dashDir = (Player.Default.transform.position - this.transform.position).normalized;
					
				}
				
			}).OnFixedUpdate(() =>
			{
				if (!AppStart.CheckGameState(GameState.GamePlaying))
				{
					return;
				}
				//冲向玩家
				selfRigidbody2D.velocity = dashDir * dashSpeed;
				
				if (fsm.FrameCountOfCurrentState>60)//冲刺2秒
				{
					//进入下个状态
					fsm.ChangeState(MiniBossState.Wait);
				}
			});
			fsm.StartState(MiniBossState.FollowPlayer);
		}

		protected override void FixedUpdate()
		{
			fsm.FixedUpdate();
			base.FixedUpdate();
			
		}
		protected override void Update()
		{
			fsm.Update();
		}
		
		
	}
}
